package com.drcoffee.drcoffeemall.task;

import com.drcoffee.drcoffeemall.feign.ErpProviderClient;
import com.drcoffee.drcoffeemall.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class OrderTask {

    private final ErpProviderClient erpProviderClient;

    private final OrderMapper orderMapper;

    public OrderTask(ErpProviderClient erpProviderClient, OrderMapper orderMapper) {
        this.erpProviderClient = erpProviderClient;
        this.orderMapper = orderMapper;
    }


    /*
     * 定时获取ERP订单编号
     * */
    @Scheduled(fixedDelay = 3600000) // 每隔一小时执行
    public void getOrderOcmCode() {
        log.info("⏰ 😎 START-TASK：获取ERP订单号.");
        try {
            List<String> ocm_code_list = orderMapper.getOrderOcmCodeByRCodeFlagIsT();
            log.info("ocm_code_list: " + ocm_code_list.toString());
            if (!ocm_code_list.isEmpty()) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("ocm_code_list", ocm_code_list);
                List<Map<String, Object>> erp_code_list = erpProviderClient.getOrderErpCode(paramMap);
                log.info("erp_code_list: " + erp_code_list.toString());
                if (!erp_code_list.isEmpty()) {
                    for (Map<String, Object> erpMap : erp_code_list) {
                        orderMapper.setOrderOcmCode(erpMap.get("OEA01").toString(), erpMap.get("OEA12").toString());
                    }
                }
            }
            log.info("⏰ 😍 SUCCESS-TASK：获取ERP订单号.");
        } catch (Exception e) {
            log.error("⏰ 🤬 ERROR-TASK-EXCEPTION：" + e.getMessage());
            e.printStackTrace();
        }
    }


    /*
     * 超过10天自动修改订单状态
     * */
    @Scheduled(cron = "0 0 0 * * ?")
    public void verifyReceiveGoods() {
        try {
            log.info("⏰ 😎 START-TASK：自动确认收货.");
            orderMapper.verifyReceiveGoods();
            log.info("⏰ 😍 SUCCESS-TASK：自动确认收货.");
        } catch (Exception e) {
            log.error("⏰ 🤬 ERROR-TASK-EXCEPTION：" + e.getMessage());
            e.printStackTrace();
        }
    }


}
